package com.hl.web;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@RestController
@RequestMapping("/file")
public class  FileUploadController {
    @RequestMapping("/upload")
    @ResponseBody
    @CrossOrigin
    public static String upload(MultipartFile file) throws IOException {
        //https://polaris-image.oss-cn-wuhan-lr.aliyuncs.com/cat1.jpg
        //endPoint: oss-cn-wuhan-lr.aliyuncs.com 地域:北京
        String endPoint = "oss-cn-beijing.aliyuncs.com";
        //用户信息
        String accessKeyId = "LTAI5tH6Xz2XWG8VUw2KcW4X";
        String accessKeySecret = "Jyep2u0zLQRlLvTYodYDmM7qdoBec8";
        //存储空间名称
        String bucketName = "gaoqiping";
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);
        // 上传文件流。
        InputStream inputStream = file.getInputStream();
        //文件原名
        String fileName = file.getOriginalFilename();
        //生成随机文件名
        fileName = UUID.randomUUID().toString().replace("-", "") + fileName;
        //上传文件流
        ossClient.putObject(bucketName, fileName, inputStream);
        //关闭OSSClient。
        ossClient.shutdown();
        String path ="https://" + bucketName + "." + endPoint + "/" + fileName;
        //返回文件路径
        return "https://" + bucketName + "." + endPoint + "/" + fileName;
    }
}
